﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.WebControls;
using System.Text;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class MyBills_ZK : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnSaveSubItems.Visible = true; btnCancelSaveSubItems.Visible = false; 
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", ""));


                if (ddlCompany.SelectedValue != null && ddlCompany.SelectedValue != "")
                {
                    BudgetBll bll = new BudgetBll();
                    string UnlockYearmonth = bll.GetunAdjustMonth(ddlCompany.SelectedValue);
                    ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                    ddlBudgetYear.SelectedValue = UnlockYearmonth.Substring(0, 4).ToString();
                }


                BindGrid(1);
                Calculate();

            }
        }

        private void SetStatus(string company, string sYear, string sMonth)
        {
            BudgetBll bll = new BudgetBll();
            if (bll.BillAdjustStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "已关账！";
                hidMsg.Value = "1";
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
                btnSaveSubItems.Visible = false;
                btnCancelSaveSubItems.Visible = false;
            }
            else
            {
                msg.Text = "";
                hidMsg.Value = "0";
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
                btnSaveSubItems.Visible = true;
                btnCancelSaveSubItems.Visible = true;
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();

            if (rbAdjust.SelectedValue == "0") {
                if (hidMsg.Value == "0")
                {
                    btnSaveSubItems.Visible = true;
                }
                else { btnSaveSubItems.Visible = false; }
                btnCancelSaveSubItems.Visible = false; }
            else { 
                btnSaveSubItems.Visible = false;
                if (hidMsg.Value == "0")
                {
                    btnCancelSaveSubItems.Visible = true;
                }
                else { btnCancelSaveSubItems.Visible = false; }
            }

            txtcBVCode.Value = "";
            refreshBills();
        }

        private void refreshBills()
        {
            BillBll bll = new BillBll();

            DataTable dt = bll.GetSalesBills("  and instrumentName <> '现金折扣' and cBVCode = '" + txtcBVCode.Value + "'", "cBVCode");
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }
        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {
            if (txtcBVCode.Value == "") return;
            refreshBills();
            
            
        }

        protected void btnSaveSubItems_Click(object sender, EventArgs e)
        {
            BudgetBll bll = new BudgetBll();

            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "出错提示！", "alert('请选择开票公司。');", true);
                return;
            }
            if (bll.BillAdjustStatus(sYear, sMonth, company) == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "出错提示！", "alert('选择月份的销售数据调整已关闭。');", true);
                return;
            }

            List<BGSalesBillsEntity> items = new List<BGSalesBillsEntity>();
            
            decimal sumAdjust = 0 ;
            int adjustNum = 0;
            foreach (GridItem item in RadGrid1.Items)
            {
                if (item.ItemType == GridItemType.Item || item.ItemType == GridItemType.AlternatingItem)
                {
                    Guid ItemID = new Guid(item.OwnerTableView.DataKeyValues[item.ItemIndex]["billGUID"].ToString());

                    RadNumericTextBox txtiNatSum_adjust = item.FindControl("txtiNatSum_adjust") as RadNumericTextBox; //折扣分摊
                    
                    decimal Adjust = 0;

                    if (txtiNatSum_adjust.Value.HasValue)
                    {
                        Adjust = (decimal)txtiNatSum_adjust.Value.Value;
                        sumAdjust += Adjust;
                        if (Adjust != 0) { adjustNum++; }
                    }

                    BGSalesBillsEntity sub = bll.Get<BGSalesBillsEntity>(ItemID);
                    sub.iNatSum_adjust = Adjust;
                    sub.UpdatedOn = System.DateTime.Now;
                    sub.Updatedby = base.CurrentUserID;
                    items.Add(sub);
                }
            }

            if (adjustNum == 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "出错提示！", "alert('请输入折扣分摊金额。');", true);
                return;
            }

            if (sumAdjust != 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "出错提示！", "alert('折扣分摊后金额与原折扣金额不符。');", true);
                return;
            }
            bll.UpdateSalesBills(items);

            ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('折扣分摊成功。');", true);
            BindGrid(1);
        }

        protected void btnCancelSaveSubItems_Click(object sender, EventArgs e)
        {
            BudgetBll bll = new BudgetBll();
            List<BGSalesBillsEntity> items = new List<BGSalesBillsEntity>();

            foreach (GridItem item in RadGrid1.Items)
            {
                if (item.ItemType == GridItemType.Item || item.ItemType == GridItemType.AlternatingItem)
                {
                    Guid ItemID = new Guid(item.OwnerTableView.DataKeyValues[item.ItemIndex]["billGUID"].ToString());

                    BGSalesBillsEntity sub = bll.Get<BGSalesBillsEntity>(ItemID);
                    sub.iNatSum_adjust = 0;
                    sub.UpdatedOn = System.DateTime.Now;
                    sub.Updatedby = base.CurrentUserID;
                    items.Add(sub);
                }
            }

            bll.UpdateSalesBills(items);

            ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('成功取消折扣分摊！');", true);
            BindGrid(1);
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().GetSalesZKBills(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
            AspNetPager1.RecordCount = RecordCount;
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcbillZKAmount(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = "合计折扣：" + string.Format("{0:N}", dt.Rows[0]["iNatSum"]);


            }
            else
            {

                lblTotal.Text = "";
            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

            sb.Append(" and a.cCusCode not in(select customerCode from cms_Bg_InnerCustomer)  and a.instrumentName <> '现金折扣' and instrumentName like '%折扣%'");
            if (rbAdjust.SelectedValue == "0")
            { sb.Append(" and a.iNatSum_adjust= 0"); }
            else
            { sb.Append(" and a.iNatSum_adjust<> 0"); }
            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(year,a.[dDate])  = ").Append(ddlBudgetYear.SelectedValue).Append("");
            }

            if (ddlBudgetMonth.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(month,a.[dDate])  = ").Append(ddlBudgetMonth.SelectedValue).Append("");
            }

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and c.[CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            //int RecordCount = 0;
            //RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (RecordCount == 0)
            //{ sb.Append(" and ([productmanager] ='").Append(base.CurrentUserEntity.UserName).Append("'").Append(" or [biller] ='").Append(base.CurrentUserID.ToString()).Append("')"); }
            //else
            //{ sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))"); }

            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            //if (ddlDept.SelectedValue != "0")
            //{ sb.Append(" and [SalesGroup] ='").Append(ddlDept.SelectedValue.ToString()).Append("'"); }


            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and customerID in(").Append("select customerid from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }
            
            //if (txtSales.Text.Trim() != "")
            //{
            //    sb.Append(" and sales = '").Append(txtSales.Text.Trim()).Append("'");
            //}
            sb.Append(" and billUnit in (select d.DepartmentName from Cms_Sys_UserDepartment_DataRight a inner join Cms_Sys_Department d on d.DepartmentID = a.DepartmentID where d.isCompany = 1 and a.UserID = '" + base.CurrentUserID.ToString() + "')");

            return sb.ToString();
        }

        protected void gridContractItems_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                if (dv != null)
                {
                    RadNumericTextBox txtiNatSum_adjust = e.Item.FindControl("txtiNatSum_adjust") as RadNumericTextBox;
                    if (dv["CategoryName"].ToString().Contains("折扣"))
                    { 
                        txtiNatSum_adjust.Value = Convert.ToDouble(dv["iNatSum"].ToString())*(-1);
                        txtiNatSum_adjust.Enabled = false;
                    }
                    else
                    {
                        txtiNatSum_adjust.Value = Convert.ToDouble(dv["iNatSum_adjust"].ToString());
                    }
                }
            }
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BillBll bll = new BillBll();

            DataTable dt = bll.GetSalesZKBills_export(Whereclause, " [客户] asc ");

            Export.Export2Excel(dt, "折扣预算一览表", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        protected void Button4_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                msg.Text = "请选择开票公司。";
                return;
            }

            if (bll.BillAdjustStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "选择月份的折扣分摊已关闭。";
                return;
            }

            bll.setDataAdjustStatus(sYear, sMonth, company, "1", base.CurrentUserEntity.UserName, DateTime.Now);
            msg.Text = "成功关闭折扣分摊。";
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != null && ddlCompany.SelectedValue != "")
            {
                BudgetBll bll = new BudgetBll();
                string UnlockYearmonth = bll.GetunAdjustMonth(ddlCompany.SelectedValue);
                ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                ddlBudgetYear.SelectedValue = UnlockYearmonth.Substring(0, 4);
            }

            if (ddlBudgetMonth.SelectedValue !="" && ddlCompany.SelectedValue != "")
            {
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
                SetStatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);

            }
            else
            {
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
            }

        }

        protected void ddlBudgetMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBudgetMonth.SelectedValue != "" && ddlCompany.SelectedValue != "")
            {
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
                SetStatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);

            }
            else
            {
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
            }
        }

        protected void ddlBudgetYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBudgetMonth.SelectedValue != "" && ddlCompany.SelectedValue != "")
            {
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
                SetStatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);

            }
            else
            {
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
            }
        }
    }
}
